import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import javax.print.DocFlavor;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author lianghao
 * @create 2019-12-14 18:00
 */
public class MqApplication {
    public static void main(String[] args) throws IOException {
//        String out = "https://www.cnblogs.com/blog5277/p/6704288.html";
        String out = "https://tool.oschina.net/commons?type=2";
        final String doc = getDoc(out);

//        getDocJsoup(out);
//        System.out.println(doc);
        System.out.println(getTitle(doc));
        System.out.println(getDescription(doc));
    }

    private static String getDescription(String content) {
        int hopeSize = 200;
        int strongSize = 50;
        int begin = content.indexOf("<meta name=\"description\" content=\"");
        if (begin > -1 && begin + hopeSize <= content.length() - begin - hopeSize) {
            begin += 34;
            String resultValue = content.substring(begin, begin + hopeSize);
            final int i = resultValue.indexOf("/>");
            resultValue = resultValue.substring(0, (resultValue.length() - i - 1) * 2 - 1);
            if (resultValue.length() > strongSize)
                resultValue = resultValue.substring(0, strongSize);
            return resultValue;
        } else
            return null;
    }

    private static String getTitle(String content) {
        int begin = content.indexOf(String.format("<%s>", "title"));
        int end = content.indexOf(String.format("</%s>", "title"));
        if (begin + 7 < end)
            return content.substring(begin + 7, end);
        else
            return null;
    }

    private static void getDocJsoup(String outurl) {
        Document doc = Jsoup.parseBodyFragment(outurl);
//        Element description =doc.getElementsByTag("0").get(0);//得到第一个a标签内容
        Element html = doc.getElementsByTag("html").get(0);//得到第一个a标签内容
        if (html != null) {
            System.out.println(html.attr("title"));
        }
    }

    private static String getDoc(String outurl) throws IOException {
        URL url = new URL(outurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        InputStream inputStream = conn.getInputStream(); //通过输入流获得网站数据
        byte[] getData = readInputStream(inputStream); //获得网站的二进制数据
        String data = new String(getData, "utf-8");
        return data;
    }

    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

}
